//操作mysql数据库
const { conn ,execcmd} = require('../conn/db')
async function getTodoList() {

    // 先去缓存里查找，有的话，直接从缓存读取，没有的话，从数据库读取，再存到缓存以便下次请求时使用
    const sql1 = 'select * from todolist';
    const result = await execcmd(sql1)
    const myarray = JSON.parse(JSON.stringify(result))   //RowDataPacket
    return myarray

    //存到缓存，后面从缓存里面获取
}


async function add(todoitem) {
    const addSql = "INSERT INTO todolist(itemname,state,userid)VALUES(?,?,?)";


    const result = await execcmd(addSql, [todoitem.itemname, todoitem.state,todoitem.userid])

    if (result && result.affectedRows > 0) {
        return await  getSingle(result.insertId)
    }
    else return null
    

}


async function edit(todoitem) {
    const editSql = "UPDATE todolist SET itemname = ?,state=? WHERE id = ?";

    const result = await execcmd(editSql, [todoitem.itemname, todoitem.state, todoitem.id])
   
    if (result && result.affectedRows > 0) {
        return await  getSingle( todoitem.id)
    }
    else return null

}

async function del(id) {
    const delSql = "DELETE from todolist WHERE id = ?";

    const result = await execcmd(delSql, [id])
    console.log(id)
    console.log(result)
    return result
}


async function getSingle(id) {
    const sql1 = 'select * from todolist where id = ?';

    const result = await execcmd(sql1, [id])
   // console.log(result)
    return result[0]
}



module.exports = { getTodoList, add, edit, del }